<?php

namespace App\Models\Customer;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use App\Models\Basic\RegionProvince;
use Illuminate\Support\Facades\Auth;

class CustomerDepartment extends BaseModel
{

    protected $table = 'customer_departments';
    protected $fillable = [
        'customer_id', 'title', 'code', 'description', 'phone', 'email', 'state', 'field', 'salesman', 'region', 'province',
        'rank', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = [];
    public $params = [];

    public function region()
    {
        return $this->belongsTo('App\Models\Basic\Region', 'region');
    }

    public function province()
    {
        return $this->belongsTo('App\Models\Basic\RegionProvince', 'province');
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function salesman()
    {
        return $this->belongsTo('App\Models\Account\User', 'salesman');
    }

    public function customer()
    {
        return $this->belongsTo('App\Models\Customer\Customer', 'customer_id');
    }

    public function field()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'field', 'code');
    }

    /**
     * 添加部门/科室
     * @param $data
     * @return null
     */
    public function addCustomerDepartment($data)
    {
        //同一客户下部门/科室名称唯一
        $title = $this->where('customer_id', $data['customer_id'])->where('title', $data['title'])->count();

        if ($title > 0) {
            return null;
        }

        //专业领域
        if (isset($data['field'])) {
            $filed = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'zyly');
            })->where('code', $data['field'])->count();
            if ($filed < 1) {
                return Code::INSIDE_ERROR_1;
            }
        }

        $province = RegionProvince::where('region_id', $data['region'])->where('id', $data['province'])->count();
        if ($province < 1) {
            return Code::INSIDE_ERROR;
        }

        //拼接code
        $code = $this->orderBy('code', 'desc')->limit(1)->first(['code']);
        if ($code) {
            $data['code'] = 'NKS' . str_pad(substr($code->code,3) + 1, 5, 0, STR_PAD_LEFT);
        } else {
            $data['code'] = 'NKS00001';
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑部门/科室
     * @param $data
     * @param $id
     * @return int|null
     */
    public function editCustomerDepartment($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //专业领域
        if (isset($data['field'])) {
            $filed = DictionaryMember::whereHas('dictionary', function ($dictionary) {
                $dictionary->where('code', 'zyly');
            })->where('code', $data['field'])->count();
            if ($filed < 1) {
                return Code::INSIDE_ERROR_2;
            }
        }

        //大区与省区关系
        $region = $data['region'] ?? $model->region;
        $province = $data['province'] ?? $model->province;
        $provinceCheck = RegionProvince::where('region_id', $region)->where('id', $province)->count();
        if ($provinceCheck < 1) {
            return Code::INSIDE_ERROR_1;
        }

        //同一客户下部门/科室名称唯一
        if (isset($data['customer_id']) && isset($data['title'])) {
            $title = $this->where('customer_id', $data['customer_id'])->where('title', $data['title'])->where('id', '!=', $id)->count();
            if ($title > 0) {
                return Code::INSIDE_ERROR;
            }
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取部门/科室详情
     * @param $id
     * @return null
     */
    public function getCustomerDepartment($id)
    {
        $model = $this->with([
            'region:id,title',
            'province:id,title',
            'createdBy:id,username',
            'salesman:id,username',
            'customer:id,title',
            'field:code,title'
        ])->find($id, [
            'id', 'customer_id', 'title', 'code', 'description', 'phone', 'email', 'state', 'field', 'salesman', 'region', 'province',
            'rank', 'created_by'
        ]);

        if (!$model) {
            return null;
        }

        return $model;
    }

}
